package com.rzico.sbl.ui.manager

import android.os.Bundle
import android.os.PersistableBundle
import android.os.SystemClock
import android.view.animation.BounceInterpolator
import androidx.lifecycle.lifecycleScope
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.amap.api.maps.model.animation.TranslateAnimation
import com.amap.api.setAnimateCamera
import com.amap.api.setCameraChangeListener
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMasterMapBinding
import com.rzico.sbl.model.MasterData
import com.rzico.sbl.viewmodel.MasterViewModel
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getByteFromAssets
import com.xinnuo.common.extend.getExtra
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeByFinally
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap


class MasterMapActivity : BaseActivity(R.layout.activity_master_map) {

    private val mBinding by lazy { ActivityMasterMapBinding.bind(getRootView()) }

    override fun getViewModel() = get<MasterViewModel>()

    // 店铺、配送信息
    private val mFixMap = ConcurrentHashMap<String, MasterData>()

    // 员工信息
    private val mChangeMap = ConcurrentHashMap<String, MasterData>()

    // 员工打点位置
    private val mChangeMarker = ConcurrentHashMap<String, Marker>()

    override fun initData() {
        initTitle(title = "实时位置")

        mBinding
            .masterBottom
            .bottomHide(
                dpValue = 50f,
                duration = 50
            )

        initAmap()
    }

    private fun initAmap() {
        mBinding.masterMap.map.apply {
            uiSettings.apply {
                isZoomControlsEnabled = false     //缩放按钮，默认打开
                isCompassEnabled = false          //指南针，默认不显示
                isMyLocationButtonEnabled = false //定位按钮
                isScaleControlsEnabled = true     //比例尺
                isScrollGesturesEnabled = true    //滑动手势
                isZoomGesturesEnabled = true      //缩放手势
                isRotateGesturesEnabled = true    //旋转手势
                isTiltGesturesEnabled = true      //倾斜手势
                logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_RIGHT //地图logo显示在右下方
            }

            mapType = AMap.MAP_TYPE_NAVI   //导航地图模式
            isTrafficEnabled = true        //实时交通状况
            showBuildings(true)            //显示3D楼块
            showMapText(true)              //显示底图文字
            showIndoorMap(true)            //设置是否显示室内地图
            isMyLocationEnabled = false    //触发定位并显示定位层

            // 自定义地图
            setCustomMapStyle(
                CustomMapStyleOptions().apply {
                    isEnable = true
                    styleData = getByteFromAssets("style.data")
                    styleExtraData = getByteFromAssets("style_extra.data")
                }
            )

            // 地图加载完成监听
            setOnMapLoadedListener {
                getLocationList { getShopList() }
            }

            // 地图状态的监听
            setCameraChangeListener {
                onCameraChange {
                    mBinding
                        .masterBottom
                        .bottomHide(50f)
                }
            }

            // marker点击事件监听
            setOnMarkerClickListener {
                mBinding
                    .masterBottom
                    .bottomShow()

                val typeList = it.snippet.split(",")
                updateBottom(
                    typeList[0],
                    when (typeList[0]) {
                        "2" -> mChangeMap[typeList[1]]
                        else -> mFixMap[typeList[1]]
                    }
                )

                startDropAnimation(it)

                true
            }

            // moveCamera(CameraUpdateFactory.changeTilt(60f)) //设置地图倾斜度，单位角度，范围（0,60）
            // moveCamera(CameraUpdateFactory.zoomTo(18f)) //设置地图缩放级别
            moveCamera(CameraUpdateFactory.newLatLng(LatLng(34.7466, 113.625367))) //默认显示郑州经纬度
        }
    }

    /**
     * 更新底部显示
     */
    private fun updateBottom(type: String, data: MasterData?) {
        data?.let {
            mBinding.apply {
                when (type) {
                    "0" -> {
                        masterImg.setImageResource(R.mipmap.icon_manager22)
                        masterTitle.text = it.name
                        masterPhone.text = "${it.linkman}    ${it.telephone}"
                        masterAdress.text = "地址: ${it.address}"
                    }
                    "1" -> {
                        masterImg.setImageResource(R.mipmap.icon_manager23)
                        masterTitle.text = it.name
                        masterPhone.text = "电话: ${it.mobile}"
                        masterAdress.text = "地址: ${it.address}"
                    }
                    "2" -> {
                        when (it.roleId) {
                            "1", "2" -> masterImg.setImageResource(R.mipmap.icon_manager05)
                            "10" -> masterImg.setImageResource(R.mipmap.icon_manager31)
                            "3" -> masterImg.setImageResource(R.mipmap.icon_manager04)
                            "4" -> masterImg.setImageResource(R.mipmap.icon_manager06)
                        }
                        masterTitle.text = "${it.name}(${it.roleName})"
                        masterPhone.text = "电话: ${it.mobile}"
                        masterAdress.text = "店铺: ${it.shopName}"
                    }
                }
            }
        }
    }

    /**
     * 每隔5s更新一次位置
     */
    private fun getLocationWithTime() {
        lifecycleScope.launch {
            while (true) {
                delay(5000)

                getLocationList()
            }
        }
    }

    /**
     * 店铺列表
     */
    private fun getShopList() {
        getViewModel()
            .masterShop(false)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mBinding.masterMap.map.apply {
                        list.forEach { mFixMap[it.id] = it }

                        if (intent.getExtra("from") == "ship") {
                            mFixMap["receive"] = MasterData(
                                id = "receive",
                                name = intent.getExtra("receiveName"),
                                mobile = intent.getExtra("receivePhone"),
                                address = intent.getExtra("receiveAdress"),
                                lat = intent.getExtra("receiveLat"),
                                lng = intent.getExtra("receiveLng")
                            )
                        }

                        val bounds = LatLngBounds
                            .Builder()
                            .apply {
                                mFixMap
                                    .values
                                    .forEach {
                                        include(LatLng(it.lat.doubleValue, it.lng.doubleValue))
                                    }

                                mChangeMap
                                    .values
                                    .forEach {
                                        include(LatLng(it.lat.doubleValue, it.lng.doubleValue))
                                    }
                            }
                            .build()

                        setAnimateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150)) {
                            onFinish {
                                mFixMap
                                    .values
                                    .forEach {
                                        addMarker(
                                            if (it.id == "receive") {
                                                MarkerOptions()
                                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_manager23))
                                                    .snippet("1,${it.id}")
                                                    .position(
                                                        LatLng(
                                                            it.lat.doubleValue,
                                                            it.lng.doubleValue
                                                        )
                                                    )
                                            } else {
                                                MarkerOptions()
                                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_manager22))
                                                    .snippet("0,${it.id}")
                                                    .position(
                                                        LatLng(
                                                            it.lat.doubleValue,
                                                            it.lng.doubleValue
                                                        )
                                                    )
                                            }
                                        )
                                    }
                            }
                        }
                    }
                },
                onFinally = { getLocationWithTime() }
            )
    }

    /**
     * 员工位置列表
     */
    private fun getLocationList(onNext: () -> Unit = {}) {
        getViewModel()
            .masterLocation()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    list.forEach { mChangeMap[it.id] = it }

                    mChangeMap
                        .values
                        .forEach {
                            if (mChangeMarker.containsKey(it.id)) {
                                // Marker位置平滑移动
                                mChangeMarker[it.id]?.apply {
                                    setAnimation(
                                        TranslateAnimation(
                                            LatLng(
                                                it.lat.doubleValue,
                                                it.lng.doubleValue
                                            )
                                        ).apply { setDuration(300) }
                                    )

                                    startAnimation()
                                }
                            } else {
                                // 添加Marker点
                                val marker = mBinding.masterMap.map.addMarker(
                                    MarkerOptions()
                                        .icon(
                                            BitmapDescriptorFactory.fromResource(
                                                when (it.roleId) {
                                                    "1", "2" -> R.mipmap.icon_manager05
                                                    "4" -> R.mipmap.icon_manager06
                                                    "10" -> R.mipmap.icon_manager31
                                                    else -> R.mipmap.icon_manager04
                                                }
                                            )
                                        )
                                        .snippet("2,${it.id}")
                                        .position(
                                            LatLng(
                                                it.lat.doubleValue,
                                                it.lng.doubleValue
                                            )
                                        )
                                )

                                mChangeMarker[it.id] = marker
                            }
                        }
                },
                onFinally = onNext
            )
    }

    /**
     * Marker点击跳动动画
     */
    private fun startDropAnimation(marker: Marker, duration: Long = 1500) {
        val start = SystemClock.uptimeMillis()
        val project = mBinding.masterMap.map.projection
        val markerLatLng = marker.position
        val markerPoint = project.toScreenLocation(markerLatLng)
        markerPoint.offset(0, -100)
        val startLatLng = project.fromScreenLocation(markerPoint)
        val interpolator = BounceInterpolator()

        lifecycleScope.launch(Dispatchers.IO) {
            var elapsed = SystemClock.uptimeMillis() - start
            var t = interpolator.getInterpolation(elapsed.toFloat() / duration)

            while (t < 1.0) {
                val lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude
                val lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude

                withContext(Dispatchers.Main) {
                    marker.position = LatLng(lat, lng)
                }

                delay(16)

                elapsed = SystemClock.uptimeMillis() - start
                t = interpolator.getInterpolation(elapsed.toFloat() / duration)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mBinding.masterMap.onCreate(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        // onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mBinding.masterMap.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        // onResume时执行mMapView.onResume ()，重新绘制加载地图
        mBinding.masterMap.onResume()
    }

    override fun onPause() {
        super.onPause()
        // onPause时执行mMapView.onPause ()，暂停地图的绘制
        mBinding.masterMap.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // onDestroy时执行mMapView.onDestroy()，销毁地图
        mBinding.masterMap.onDestroy()
    }

}